package logic

import (
	"C/Rpc/internal/svc"
	"C/Rpc/model/Es"
	"C/Rpc/model/mysql"
	"C/Rpc/shop"
	"bytes"
	"context"
	"encoding/json"
	"github.com/elastic/go-elasticsearch/v7/esapi"
	"log"
	"strconv"
	"sync"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSyncToLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSyncToLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSyncToLogic {
	return &EsSyncToLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// es同步
func (l *EsSyncToLogic) EsSyncTo(in *shop.EsSyncToRequest) (*shop.EsSyncToResponse, error) {
	// todo: add your logic here and delete this line
	var (
		list []mysql.Good
		wg   sync.WaitGroup
	)
	for _, goods := range list {
		wg.Add(1)

		go func(goods mysql.Good) {
			defer wg.Done()

			// Build the request body.
			data, err := json.Marshal(goods)
			if err != nil {
				log.Fatalf("Error marshaling document: %s", err)
			}

			// Set up the request object.
			req := esapi.IndexRequest{
				Index:      "goods",
				DocumentID: strconv.Itoa(int(goods.ID)),
				Body:       bytes.NewReader(data),
				Refresh:    "true",
			}

			// Perform the request with the client.
			res, err := req.Do(context.Background(), Es.Es)
			if err != nil {
				log.Fatalf("Error getting response: %s", err)
			}
			defer res.Body.Close()

		}(goods)
	}
	wg.Wait()
	return &shop.EsSyncToResponse{}, nil
}
